package top.lyc829.zzl_android.ui.thing.dynamic;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Response;
import top.lyc829.zzl_android.MyApp;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.DynamicFragmentBinding;
import top.lyc829.zzl_android.logic.bean.BaseDetailBean;
import top.lyc829.zzl_android.logic.bean.DynamicBean;
import top.lyc829.zzl_android.logic.bean.LiveEventMsg;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.ShareBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.DynamicType;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.ReplayType;
import top.lyc829.zzl_android.logic.util.Url;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.base_detail.BaseDetailActivity;
import top.lyc829.zzl_android.ui.custom_view.ShareMsgDialog;
import top.lyc829.zzl_android.ui.profile.follow.user_detail.OtherUserDetailActivity;
import top.lyc829.zzl_android.ui.thing.ThingViewModel;
import top.lyc829.zzl_android.ui.thing.dynamic_detail.DynamicDetailActivity;
import top.lyc829.zzl_android.ui.thing.travel_detail.TravelDetailActivity;

public class DynamicFragment extends Fragment {

    private DynamicFragmentBinding binding;
    private DynamicViewModel mViewModel;
    private ThingViewModel thingViewModel;
    private DynamicRecyclerViewAdapter1 adapter;
    PageInfo pageInfo;
    ShareMsgDialog shareMsgDialog;
    MaterialDialog loadingDialog;

    BottomSheetDialog dialog;

    public static DynamicFragment newInstance() {
        return new DynamicFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        binding = DynamicFragmentBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(DynamicViewModel.class);
        thingViewModel = new ViewModelProvider(requireActivity()).get(ThingViewModel.class);
        pageInfo = new PageInfo();
        LiveEventBus
                .get("logout", Integer.class)
                .observeSticky(this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        if (integer.equals(1)) {
                            Utils.Sout("接收到注销消息");
                            pageInfo.reset();
                            if (adapter != null) {
                                binding.dynamicRecyclerview.scrollToPosition(0);
                                binding.refreshLayout.autoRefresh();
                            }

                        }
                    }
                });

        LiveEventBus
                .get("login", Integer.class)
                .observeSticky(this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        if (integer.equals(1)) {
                            Utils.Sout("接收到登录消息");
                            pageInfo.reset();
                            if (adapter != null) {
                                binding.dynamicRecyclerview.scrollToPosition(0);
                                binding.refreshLayout.autoRefresh();
                            }

                        }
                    }
                });


        // 实例化加载框
        loadingDialog = new MaterialDialog.Builder(getContext())
                .customView(R.layout.dialog_loading_layout, true)
                .cancelable(false)
                .build();


        initDynamicRecyclerViewAdapter();
        init();

        observer();
        sendRequest();

        clickListener();

    }

    /**
     * 控件点击事件监听
     */
    private void clickListener() {

        adapter.setOnItemClickListener(new RecyclerViewHolder.OnItemClickListener<DynamicBean>() {
            @Override
            public void onItemClick(View itemView, DynamicBean item, int position) {
                Intent intent = new Intent(getActivity(), DynamicDetailActivity.class);
                intent.putExtra("id", adapter.getData().get(position).getDynamicId());
                intent.putExtra("position", position);
                intent.putExtra("type", 0); //0-动态页进去 1-关注页面进去
                startActivity(intent);
            }
        });

        adapter.setOnItemLongClickListener((itemView, item, position) -> {

            //Utils.showToast(adapter.getItem(position).getDynamicId().toString());
            mViewModel.getDeletePositionLiveData().setValue(position);
            showBottomDialog();
        });

        // 子view的点击事件
        adapter.setOnItemChildClickListener((holder, view, position) -> {
            if (view.getId() == R.id.dynamic_praise) {
                if (!Utils.isLogin()) {
                    Utils.showToast("请先登录");
                    return;
                }
                if (mViewModel.getDynamicLiveData().getValue() != null) {
                    final DynamicBean dynamicBean = adapter.getItem(position);
                    View itemView = binding.dynamicRecyclerview.getLayoutManager().findViewByPosition(position);
                    // 点击后设置不可点击
                    itemView.findViewById(R.id.dynamic_praise).setClickable(false);
                    if (dynamicBean.getIsLike().equals(0)) {
                        sendLike(Utils.getUserId(), dynamicBean.getDynamicId(), position);
                    } else {
                        sendUnLike(Utils.getUserId(), dynamicBean.getDynamicId(), position);
                    }
                }

            } else if (view.getId() == R.id.dynamic_share) {
                shareToDynamic(position);
            } else if (view.getId() == R.id.dynamic_comment) {
                Intent intent = new Intent(getActivity(), DynamicDetailActivity.class);
                intent.putExtra("id", adapter.getData().get(position).getDynamicId());
                intent.putExtra("position", position);
                intent.putExtra("is_comment", true);
                startActivity(intent);
            } else if (view.getId() == R.id.edit_share) {
                goOriginDynamic(position);
            } else if (view.getId() == R.id.my_dynamic_user_Url) {
                Intent intent = new Intent(getActivity(), OtherUserDetailActivity.class);
                intent.putExtra("id", adapter.getItem(position).getUserId());
                startActivity(intent);
            }

        });


    }

    // 去原始动态
    private void goOriginDynamic(int position) {
        DynamicBean item = adapter.getItem(position);
        Intent intent = null;
        if (item.getType().equals(DynamicType.BASE)) {
            intent  = new Intent(getActivity(), BaseDetailActivity.class);
            intent.putExtra("id", item.getTypeId());
        } else if (item.getType().equals(DynamicType.DYNAMIC)) {
            intent  = new Intent(getActivity(), DynamicDetailActivity.class);
            intent.putExtra("id", item.getTypeId());
        }else if (item.getType().equals(DynamicType.TRAVEL)) {
            intent  = new Intent(getActivity(), TravelDetailActivity.class);
            intent.putExtra("travel_id", item.getTypeId());
        }
        if (intent != null) {
            startActivity(intent);
        }
    }


    /**
     * 弹出底部弹窗
     */
    private void showBottomDialog() {
        int position = mViewModel.getDeletePositionLiveData().getValue();
        if (Utils.getUserId() != adapter.getItem(position).getUserId()) {
            return;
        }
        if (dialog == null) {
            dialog = new BottomSheetDialog(getContext(), R.style.MyBottomSheetDialog);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.bottom_sheet_dialog_dynamic_long_click, null);

            view.findViewById(R.id.dynamic_long_delete).setOnClickListener(v -> {
                deleteDynamic();
                dialog.dismiss();
            });

            view.findViewById(R.id.dynamic_long_cancel).setOnClickListener(v -> {
                dialog.dismiss();
            });

            dialog.setContentView(view);
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(true);
        }
        dialog.show();

    }

    /**
     * 删除动态
     */
    private void deleteDynamic() {
        if (mViewModel.getDeletePositionLiveData().getValue() == null) {
            return;
        }
        int position = mViewModel.getDeletePositionLiveData().getValue();

        Network.deleteDynamic(Utils.getUserId(), adapter.getItem(position).getDynamicId(), new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resStr = res.body().string();
                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                if (resultBean.getCode().equals(200)) {
                    getActivity().runOnUiThread(() -> {
                        Utils.showToast("删除成功");
                        adapter.delete(position);
                        adapter.notifyDataSetChanged();
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
            }
        });
    }

    private void shareToDynamic(int position) {
        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
            return;
        }

        if (shareMsgDialog != null) {
            shareMsgDialog = null;
        }

        if (shareMsgDialog == null) {
            DynamicBean dynamic = adapter.getItem(position);

            shareMsgDialog = new ShareMsgDialog(
                    getContext(),
                    R.style.dialog_center,
                    new ShareBean(dynamic.getUserName(), dynamic.getDynamicText() ,dynamic.getDynamicUrl().get(0)));
            shareMsgDialog.setmOnTextSendListener(msg -> {
                shareMsgDialog.dismiss();
                loadingDialog.show();

                Network.shareToDynamic(DynamicType.DYNAMIC, dynamic.getDynamicId(), Utils.getUserId(), msg, new HttpUtil.MyCallback() {
                    @Override
                    public void success(Response res) throws IOException {
                        String resStr = res.body().string();
                        ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                        if (resultBean.getCode().equals(200)) {
                            getActivity().runOnUiThread(() ->{
                                loadingDialog.dismiss();
                                Utils.showToast("分享成功");
                            });
                        } else {
                            failed(new IOException(resultBean.getMsg()));
                        }
                    }

                    @Override
                    public void failed(IOException e) {
                        getActivity().runOnUiThread(() -> {
                            Utils.Sout(e.getMessage());
                            loadingDialog.dismiss();
                        });

                    }
                });

            });

        }

        shareMsgDialog.show();
    }

    private void sendLike(int userId, Integer dynamicId, int position) {
        Network.sendLike(userId, ReplayType.DYNAMIC, dynamicId, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resStr = res.body().string();
                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                if (resultBean.getCode().equals(200)) {
                    getActivity().runOnUiThread(() -> {
                        getActivity().runOnUiThread(() -> {
                            View itemView = binding.dynamicRecyclerview.getLayoutManager().findViewByPosition(position);
                            // 点击后设置不可点击
                            itemView.findViewById(R.id.dynamic_praise).setClickable(true);
                            adapter.getItem(position).setIsLike(1);
                            adapter.getItem(position).setLikes(adapter.getItem(position).getLikes() + 1);
                            adapter.notifyDataSetChanged();
                        });
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                getActivity().runOnUiThread(() -> {
                    Utils.SoutErr(e.getMessage());
                    View itemView = binding.dynamicRecyclerview.getLayoutManager().findViewByPosition(position);
                    // 点击后设置不可点击
                    if (itemView.findViewById(R.id.dynamic_praise) != null) {
                        itemView.findViewById(R.id.dynamic_praise).setClickable(true);
                    }
                });

            }
        });
    }

    private void sendUnLike(int userId, Integer dynamicId, int position) {
        Network.sendUnLike(userId, ReplayType.DYNAMIC, dynamicId, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resStr = res.body().string();
                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                if (resultBean.getCode().equals(200)) {
                    getActivity().runOnUiThread(() -> {
                        View itemView = binding.dynamicRecyclerview.getLayoutManager().findViewByPosition(position);
                        // 点击后设置不可点击
                        itemView.findViewById(R.id.dynamic_praise).setClickable(true);
                        adapter.getItem(position).setIsLike(0);
                        adapter.getItem(position).setLikes(adapter.getItem(position).getLikes() - 1);
                        adapter.notifyDataSetChanged();
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                getActivity().runOnUiThread(() -> {
                    Utils.SoutErr(e.getMessage());
                    View itemView = binding.dynamicRecyclerview.getLayoutManager().findViewByPosition(position);
                    // 点击后设置不可点击
                    if (itemView.findViewById(R.id.dynamic_praise) != null) {
                        itemView.findViewById(R.id.dynamic_praise).setClickable(true);
                    }
                });
            }
        });
    }


    public void init() {

        binding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                request();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageInfo.reset();
                request();
            }
        });

    }


    /**
     * 观察者
     */
    public void observer() {
        mViewModel.getDynamicLiveData().observe(getViewLifecycleOwner(), dynamicBeans -> {


            if (pageInfo.isFirstPage()) {
                adapter.refresh(dynamicBeans);
                binding.refreshLayout.finishRefresh();
            } else {
                adapter.loadMore(dynamicBeans);
            }

            if (dynamicBeans == null || dynamicBeans.size() < PageInfo.MAX_ITEM) {
                binding.refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                binding.refreshLayout.finishLoadMore();
                pageInfo.nextPage();
            }

        });

        thingViewModel.getDynamicDoubleClickLiveData().observe(getViewLifecycleOwner(), aBoolean -> {
            if (aBoolean) {
                binding.dynamicRecyclerview.scrollToPosition(0);
                binding.refreshLayout.autoRefresh();
            }
        });

        LiveEventBus
                .get("dynamic_praise_dynamic", LiveEventMsg.class)
                .observe(this, liveEventMsg -> {
                    int position = Integer.parseInt(liveEventMsg.getMsg().get("position"));
                    if (!adapter.getItem(position).getIsLike().equals(
                            Integer.parseInt(liveEventMsg.getMsg().get("is_like")))) {
                        adapter.getItem(position).setIsLike(Integer.parseInt(liveEventMsg.getMsg().get("is_like")));
                        int oldLikes = adapter.getItem(position).getLikes();
                        adapter.getItem(position).setLikes(
                                Integer.parseInt(liveEventMsg.getMsg().get("is_like")) == 1 ? oldLikes + 1 : oldLikes - 1);
                        adapter.notifyDataSetChanged();
                    }
                });
        LiveEventBus
                .get("dynamic_comment_dynamic", LiveEventMsg.class)
                .observe(this, liveEventMsg -> {
                    Utils.Sout(liveEventMsg.toString());
                    int position = Integer.parseInt(liveEventMsg.getMsg().get("position"));
                    if (!adapter.getItem(position).getComments().equals(
                            Integer.parseInt(liveEventMsg.getMsg().get("comments")))) {

                        DynamicBean dynamic = adapter.getItem(position);
                        dynamic.setComments(Integer.parseInt(liveEventMsg.getMsg().get("comments")));
                        adapter.notifyDataSetChanged();
                    }
                });

    }

    /**
     * 发送请求
     */
    public void sendRequest() {


    }




    // 初始化动态卡片
    private void initDynamicRecyclerViewAdapter() {
        adapter = new DynamicRecyclerViewAdapter1();
        binding.dynamicRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.dynamicRecyclerview.setAdapter(adapter);
        // 防止图片复用
        binding.dynamicRecyclerview.setItemViewCacheSize(1000);
        binding.refreshLayout.autoRefresh();
    }



    private void request() {
        try {
            mViewModel.getDynamics(pageInfo.getPage());
        } catch (Exception e) {
            Utils.Sout(e.getMessage());
        }

    }


    @Override
    public void onResume() {
        super.onResume();
    }
}